#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
using namespace std;
int buffer[4]={0}, writepos=0, readpos=0, room = 4;
char ch = 'a';
pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t _thread1_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t _thread2_cond = PTHREAD_COND_INITIALIZER;
void *thread1_routine(void *arg)
{
	while (1)
	{
		pthread_mutex_lock(&_mutex);
		while (room == 0) 
		{
			pthread_cond_wait(&_thread1_cond, &_mutex);
		}
		buffer[writepos] = ch;
		cout<<"thread1 writing : " <<"buffer[" <<writepos<<"]"<<"="<<ch<<endl;
		ch = (ch - 'a' + 1) % 26 + 'a'; // 循环字母
        writepos = (writepos + 1) % 4;
		room--;
		pthread_cond_signal(&_thread2_cond);
		// sleep(1);
		pthread_mutex_unlock(&_mutex);
	}
	return nullptr;
}

void *thread2_routine(void *arg)
{
	while (1)
	{
		pthread_mutex_lock(&_mutex);
		while (room == 4)
		{
			pthread_cond_wait(&_thread2_cond, &_mutex);
		}
		cout << "thread2 reading : "<<(char)buffer[readpos] << endl;
		readpos = (readpos + 1) % 4;
		room++;
		pthread_cond_signal(&_thread1_cond);
		pthread_mutex_unlock(&_mutex);	
	}
	return nullptr;
}

int main()
{
	pthread_t pid1, pid2;
	if (pthread_create(&pid1, nullptr, thread1_routine, nullptr))
	{
		perror("pthread_create1 error");
		return 1;
	}
	if (pthread_create(&pid2, nullptr, thread2_routine, nullptr))
	{
		perror("pthread_create2 error");
		return 1;
	}
	pthread_join(pid1, nullptr);
	pthread_join(pid2, nullptr);
}
